<?php
//微信用户相关

namespace App\Http\Controllers;

use App\Repositories\FollowRepository;
use Illuminate\Http\Request;
use App\Models\OperateModel;
use App\Models\KlineModel;
use App\Models\DealModel;
use App\Http\Controllers\BaseController;

class TestController extends BaseController
{
    public function test ()
    {
        $followRepository = new FollowRepository();
        $followRepository->monitor();
    }

    public function transform (Request $request)
    {
        $type = $request->input('type', 'rate');
        if ($type == 'rate') {
            $totalKey = 'total_rate';
        } else if ($type == 'money') {
            $totalKey = 'buy_money';
        }
        $page = 0;
        $bool = true;
        $close = 0;
        $saveData = [];
        $insertNumber = 20;         // 达到20条才一次插入数据库
        $insertNumberCount = 0;     // 计算插入条数
        while ($bool) {
            $operate = OperateModel::orderBy('id', 'asc')
                ->offset($page)->limit(1)->get();
            $page++;
            $insertNumberCount++;
            if (!count($operate)) {
                $bool = false;
            } else {
                if (!$operate[0]['end_at']) {
                    continue;
                }
                /*if ($operate[0]['id'] == 4) {
                    die;
                }*/
                // 这里做逻辑
                $item = $operate[0];
                if ($page === 1) {
                    $open = 0;
                } else {
                    $open = $close;
                }
                $deals = DealModel::where('operate_id', $item['id'])
//                    ->where('deal_type', DealModel::DEAL_SALE)
                    ->select('share_number', 'price', 'deal_type', 'deal_money')
                    ->get();
                $vol = 0;
                $dealMoney = 0;
                foreach ($deals as $deal) {
                    if ($deal['deal_type'] == DealModel::DEAL_BUY) {
                        $dealMoney += $deal['deal_money'];
                    } else if ($deal['deal_type'] == DealModel::DEAL_SALE) {
                        $vol += $deal['share_number'];
                    }
                }
                $costPrice = $this->getCostPrice($vol, $dealMoney);
                $beginDate = substr($item['begin_at'], 0, 10);
                $endDate = substr($item['end_at'], 0, 10);
                $stockCode = $item['code_prefix'] . $item['stock_code'];
                // datalen = 2030; 最大
//        $historyUrl = 'https://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=sz002095&scale=60&ma=no&datalen=530';
                $historyUrl = 'https://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=' . $stockCode . '&scale=60&ma=no&datalen=630';
                $contents = file_get_contents($historyUrl);
                $contents = json_decode($contents, true);
                $durations = $this->getDurationData($contents, $beginDate, $endDate, $costPrice);
                $dateHighLow = $this->getDurationDataHighLow($durations);
                $highLowRates = $this->getDurationDateHighLowRate($dateHighLow);
                $close += $item[$totalKey];
                $hideData = $highLowRates[$endDate]['high'] * 100;
                $lowData = $highLowRates[$endDate]['low'] * 100;
                $high =  ($open + $hideData) * 100;
                $low = ($open + $lowData) * 100;
//                dump($hideData);
//                dump($high . '----' . $low . '----' . $open * 100 . '----' . $close);
                $data = [
                    'admin_id' => 1,
                    'kline_type_id' => 1,
                    'type' => $type,
                    'date' => substr($item['end_at'], 0, 10),
                    'yclose' => '0',
                    'open' => $open * 100,
                    'high' => $high,
                    'low' => $low,
                    'close' => $close * 100,
                    'vol' => $vol * 100,
                    'amount' => $item['buy_money'] * 100,
                ];
                $saveData[] = $data;

                if ($insertNumber === $insertNumberCount) {
                    $insertNumberCount = 0;
                    // 批量插入
                    $model = new KlineModel();
//                    dd($saveData);
                    $result = $model->insert($saveData);
                    if (!$result) {
                        echo '插入失败,当前条数为:' . $page. '<br>';
                        die;
                    }
                    // 重置插入的数据
                    $saveData = [];
                }
//                dump($insertNumber);
            }
            // 循环结束的时候也需要将剩余的插入数据库
            if (!$bool) {
                $model = new KlineModel();
                $result = $model->insert($saveData);
                if (!$result) {
                    echo '插入失败,当前条数为:' . $page. '<br>';
                    die;
                }
            }
        }
        die;
    }

    private function getCostPrice ($vol, $costPrice) {
        return $costPrice / $vol;
    }

    private function getDurationData ($datas, $beginDate, $endDate, $buyPrice) {
        $duration = [];
        $scale = false;
        $yclose = 0;
        $open = 0;
        foreach ($datas as $data) {
            $date = substr($data['day'], 0, 10);
            if ($date == $beginDate) {
                $scale = true;
            }

            if (strtotime($date) > strtotime($endDate)) {
                $scale = false;
            }
            if ($date == $beginDate ) {
                $yclose = $data['close'];
                if (!$open) {
                    $open = $data['open'];
                }
                // 前一天涨跌数据 （(买入价 - 收盘价) / 收盘价）
//                dump($buyPrice, $yclose, $open, $data);
                $ydata = ($buyPrice - $yclose) / $open;
            }
            // 去除买入当日（不能卖出）
            if ($scale && $date != $beginDate ) {
                if ($yclose) {
                    $data['yclose'] = $yclose;
                    $data['ydata'] = $ydata;
                }
                $duration[$date][] = $data;
            }
        }
        return $duration;
    }

    /**
     * 获取每天的最高价和最低价
     * @param $datas
     * @return array
     */
    private function getDurationDataHighLow ($datas)
    {
        $high = [];
        $low = [];
        foreach ($datas as $date => $data) {
            $yclose = $data[0]['yclose'];   // 上一天的收盘价
            $ydata = $data[0]['ydata'];   // 上一天的收盘价
            $highValues = array_column($data, 'high');
            $lowValues = array_column($data, 'low');
            $maxValue = max($highValues);
            $minValue = min($lowValues);
            $high[$date] = $ydata / 10000 + ($maxValue - $yclose) / $yclose;
            $low[$date] = $ydata / 10000 + ($minValue - $yclose) / $yclose;
            if (count($datas) > 1) {
//                dump($open . '====' . $maxValue . '====' . $minValue);
//                dd($datas);
            }
        }
        return [
            'low' => $low,
            'high' => $high,
        ];
    }

     private function getDurationDateHighLowRate ($datas)
    {
        $highAndLow = [];
        foreach ($datas as $key => $data) {
            $dates = array_keys($data);
            $date = end($dates);
            if ($key === 'high') {
                $highAndLow[$date]['high'] = max($data);
            } else if ($key === 'low') {
                $highAndLow[$date]['low'] = min($data);
            }
        }
        return $highAndLow;
    }
}
